var board = new Array();
var score = 0;
var hasConflicted = new Array();
var isFirst = true;
var firstMusic = true;
var secondMusic = true;
var lastScore = 0;
var musicStart = true;
var probability = 0.6;

var startx = 0;
var starty = 0;
var endx = 0;
var endy = 0;

$(document).ready(function(){
	prepareForMobile();
	newgame();
	
	$('#dificulty-1').click(function(){
		$('#dificulty-1').css('background-color','#d5d5a0');
		$('#dificulty-2').css('background-color','#fff');
		$('#dificulty-3').css('background-color','#fff');
		$('#dificulty-1').css('color','#fff');
		$('#dificulty-2').css('color','#000');
		$('#dificulty-3').css('color','#000');
		newgame();
		probability = 0.6;
	});
	
	$('#dificulty-2').click(function(){
		$('#dificulty-1').css('background-color','#fff');
		$('#dificulty-2').css('background-color','#d5d5a0');
		$('#dificulty-3').css('background-color','#fff');
		$('#dificulty-1').css('color','#000');
		$('#dificulty-2').css('color','#fff');
		$('#dificulty-3').css('color','#000');
		newgame();
		probability = 0.85;
	});
	
	$('#dificulty-3').click(function(){
		$('#dificulty-1').css('background-color','#fff');
		$('#dificulty-2').css('background-color','#fff');
		$('#dificulty-3').css('background-color','#d5d5a0');
		$('#dificulty-1').css('color','#000');
		$('#dificulty-2').css('color','#000');
		$('#dificulty-3').css('color','#fff');
		newgame();
		probability = 0.97;
	});
});

// $('#zt').click(function(){
// 	console.log('?');
// 	theMusic();
	
// })

function prepareForMobile(){
	
	if(documentWidth > 500){
		gridContainerWidth = 500;
		cellSpace = 20;
		cellSideLength = 100;
	}
	
	$('#grade').css('font-size', gridContainerWidth * 0.045);
	$('#grade').css('top', gridContainerWidth * 0.06);
	$('#grade').css('right', gridContainerWidth * 0.09);
	
	$('.grade').css('font-size', gridContainerWidth * 0.045 );
	$('.dificulty').css('font-size', gridContainerWidth * 0.02 );
	
	$('.dificulty').css('width', gridContainerWidth * 0.14);
	$('.dificulty').css('height', gridContainerWidth * 0.05);
	$('.dificulty').css('right', gridContainerWidth * 0.06);
	$('.dificulty').css('line-height', gridContainerWidth * 0.005);
	$('#dificulty-1').css('top', gridContainerWidth * 0.14);
	$('#dificulty-2').css('top', gridContainerWidth * 0.24);
	$('#dificulty-3').css('top', gridContainerWidth * 0.34);
	
	$('header h1').css('font-size', gridContainerWidth * 0.11);
	
	$('#music').css('top',gridContainerWidth * 1.6);
	// $('#music').css('left', gridContainerWidth * 8);
	$('#music').css('width',gridContainerWidth * 0.12);
	$('#music').css('height',gridContainerWidth * 0.12);
	$('#music').css('border-radius',gridContainerWidth * 0.02);
	
	$('#music').css('top', gridContainerWidth * 1.6);
	$('#music').css('left', gridContainerWidth * 0.48);
	// $('#music').css('', gridContainerWidth * 0.01);
	
	$('#lastfen').css('top', gridContainerWidth * 1.53);
	$('#lastfen').css('left', gridContainerWidth * 0.04);
	$('#lastfen').css('font-size', gridContainerWidth * 0.04 + 'px');
	
	
	$('#lastscore').css('top', gridContainerWidth * 1.6);
	$('#lastscore').css('left', gridContainerWidth * 0.06);
	$('#lastscore').css('font-size', gridContainerWidth * 0.06 + 'px');
	$('#lastscore').css('line-height', gridContainerWidth * 0.11 + 'px');
	$('#lastscore').css('width', gridContainerWidth * 0.2);
	$('#lastscore').css('height', gridContainerWidth * 0.11);
	
	
	$('#fen').css('top', gridContainerWidth * 1.53);
	$('#fen').css('right', gridContainerWidth * 0.1);
	$('#fen').css('font-size', gridContainerWidth * 0.04 + 'px');
	
	$('#score').css('top', gridContainerWidth * 1.6);
	$('#score').css('right', gridContainerWidth * 0.04);
	$('#score').css('font-size', gridContainerWidth * 0.06 + 'px');
	$('#score').css('line-height', gridContainerWidth * 0.11 + 'px');
	$('#score').css('width', gridContainerWidth * 0.2);
	$('#score').css('height', gridContainerWidth * 0.11);
	
	$('#grid-container').css('width', gridContainerWidth - 2 * cellSpace);
	$('#grid-container').css('height', gridContainerWidth - 2 * cellSpace);
	$('#grid-container').css('padding', cellSpace);
	$('#grid-container').css('border-radius', 0.02 * gridContainerWidth);
	
	$('.grid-cell').css('width', cellSideLength);
	$('.grid-cell').css('height', cellSideLength);
	$('.grid-cell').css('border-radius', 0.02 * cellSideLength);
}

function newgame(){
	 init();
	 $("#score").css('color', '#fff');
	 score = 0;
	 isFirst = true;
	 firstMusic = true;
	 secondMusic = true;
	 updateScore(score);
	generateOneNumber();
	generateOneNumber();
}

function init(){
	for(var i = 0; i < 4; i++ ){
		for(var j = 0; j < 4; j++){
			
			var gridCell = $("#grid-cell-" + i + "-" + j);
			gridCell.css('top', getPosTop(i, j));
			gridCell.css('left', getPosLeft(i, j));
		}
	}
	for(var i = 0; i < 4; i++ ){
		board[i] = new Array();
		hasConflicted[i] = new Array();
		
		for(var j = 0; j < 4; j++){
			board[i][j] = 0;
			hasConflicted[i][j] = false;
			
		}
	}
	 updateBoardView();
}

function updateBoardView(){
	
	$(".number-cell").remove();
	for(var i = 0; i < 4; i++){
		for(var j = 0; j < 4; j++){
			$("#grid-container").append('<div class="number-cell" id="number-cell-'+i+"-"+j+'"></div>');
			var theNumberCell = $('#number-cell-'+i+'-'+j);
			
			if(board[i][j] == 0){
				theNumberCell.css('width', '0px');
				theNumberCell.css('height', '0px');
				theNumberCell.css('top', getPosTop(i, j) + cellSideLength/2);
				theNumberCell.css('left', getPosLeft(i, j) + cellSideLength/2);
			}
			else{
				theNumberCell.css('width', cellSideLength);
				theNumberCell.css('height', cellSideLength);
				theNumberCell.css('top', getPosTop(i, j));
				theNumberCell.css('left', getPosLeft(i, j));
				theNumberCell.css('background-color', getNumberBackgroundColor(board[i][j]));
				theNumberCell.css('color', getNumberColor(board[i][j]));
				// theNumberCell.text(board[i][j]);
				theNumberCell.text(theKingText(board[i][j]));
				
			}
			hasConflicted[i][j] = false;
			
			if(board[i][j] > 8000){
				theNumberCell.css('font-size', '20px');
			}
			// else if(board[i][j] >= 128 && board[i][j] < 1024){
			// 	theNumberCell.css('font-size', '50px');
			// }
		}
		$('.number-cell').css('line-height', cellSideLength + 'px');
		$('.number-cell').css('font-size', 0.4 * cellSideLength );
	}
}

function generateOneNumber(){
	
	if(nospace(board))
	return false;
	
	var randx = parseInt(Math.floor(Math.random() * 4));
	var randy = parseInt(Math.floor(Math.random() * 4));
	
	var time = 0;
	while(time < 50){
		if(board[randx][randy] == 0)
		break;
		else{
		randx = parseInt(Math.floor(Math.random() * 4));
		randy = parseInt(Math.floor(Math.random() * 4));
		}
	}
	if(time == 50){
		for(var i = 0; i < 4; i++)
			for(var j = 0; j < 4; j++)
				if(board[i][j] == 0){
					randx = x;
					randy = y;
				}
	}
	
	var randNumber = Math.random()<probability?2:4;
	
	board[randx][randy] = randNumber;
	showNumberWithAnimation(randx, randy, randNumber);
	return true;
}

$(document).keydown(function(event){
	 
	switch(event.keyCode){
		case 37:
		event.preventDefault();
			if(moveLeft()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 38:
		event.preventDefault();
			if(moveUp()){
				
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
				return false;
			}
			break;
		case 39:
		event.preventDefault();
			if(moveRight()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 40:
		event.preventDefault();
			if(moveDown()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
				return false;
			}
			break;
		case 65:
		event.preventDefault();
			if(moveLeft()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 87:
		event.preventDefault();
			if(moveUp()){
				
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 68:
		event.preventDefault();
			if(moveRight()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 83:
		event.preventDefault();
			if(moveDown()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
			break;
		case 13:
			setTimeout("newgame()",210);
			break;
		default:
			break;
	}
});

document.addEventListener('touchstart', function(event){
	startx = event.touches[0].pageX;
	starty = event.touches[0].pageY;
});

document.addEventListener('touchmove', function(event){
	event.preventDefault();
});

document.addEventListener('touchend', function(event){
	endx = event.changedTouches[0].pageX;
	endy = event.changedTouches[0].pageY;
	
	var deltax = endx - startx;
	var deltay = endy - starty;
	
	if(Math.abs(deltax) < 0.05 * documentWidth && Math.abs(deltay) < 0.05 * documentWidth)
		return;
	
	if(Math.abs(deltax) > Math.abs(deltay)){
		if(deltax > 0){
			if(moveRight()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
		}
		else{
			if(moveLeft()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
		}
	}
	else{
		if(deltay > 0){
			if(moveDown()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
		}
		else{
			if(moveUp()){
				setTimeout("generateOneNumber()",210);
				setTimeout("isgameover()",300);
			}
		}
	}
});

function isgameover(){
	if(nospace(board) && nomove(board)){
		if(secondMusic){
			var wav2 = "./music/rikka02_06.wav";
			var wav2 = new Audio(wav2);
			wav2.play();
			secondMusic = false;
		}
		gameover();
	}
		
}

function gameover(){
	if(probability == 0.6){
		if(score < 4000)
			alert("太菜了");
		else if(score > 4000 && score < 12000)
			alert("有点东西");
		else if(score > 12000)
			alert("你已经超神了！");
		if(score > lastScore){
			lastScore = score;
			$('#lastscore').text(lastScore);
		}
	}
	else if(probability == 0.85){
		if(score < 2000)
		alert("太菜了");
	else if(score > 2000 && score < 9000)
		alert("有点东西");
	else if(score > 9000)
		alert("你已经超神了！");
	if(score > lastScore){
		lastScore = score;
		$('#lastscore').text(lastScore);
		}
	}
	else{
		if(score < 1000)
			alert("太菜了");
		else if(score > 1000 && score < 10000)
			alert("有点东西");
		else if(score > 10000)
			alert("你已经超神了！");
		if(score > lastScore){
			lastScore = score;
			$('#lastscore').text(lastScore);
			}
	}
	setTimeout("newgame()",200);
}

function moveLeft(){
	if(!canMoveLeft(board))
		return false;
		
	for(var i = 0; i < 4; i++)
		for(var j = 1; j < 4; j++){
			if(board[i][j] != 0){
				
				for(var k = 0; k < j; k++){
					if(board[i][k] == 0 && noBlockHorizontal(i, k, j, board)){
						
						showMoveAnimation(i, j, i, k);
						board[i][k] = board[i][j];
						board[i][j] = 0;
						continue;
					}
					else if(board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]){
						
						showMoveAnimation(i, j, i, k);
						board[i][k] += board[i][j];
						board[i][j] = 0;
						
						score += board[i][k];
						updateScore(score);
						hasConflicted[i][k] = true;
						continue;
					}
				}
			}
		}
	setTimeout("updateBoardView()", 200);
	
	return true;
}

function moveUp(){
	if(!canMoveUp(board))
		return false;
		
	for(var j = 0; j < 4; j++)
		for(var i = 1; i < 4; i++){
			if(board[i][j] != 0){
				
				for(var k = 0; k < i; k++){
					if(board[k][j] == 0 && noBlockVertical(j, k, i, board)){
						
						showMoveAnimation(i, j, k, j);
						board[k][j] = board[i][j];
						board[i][j] = 0;
						continue;
					}
					else if(board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasConflicted[k][j]){
						
						showMoveAnimation(i, j, k, j);
						board[k][j] += board[i][j];
						board[i][j] = 0;

						score += board[k][j];
						updateScore(score);
						hasConflicted[k][j] = true;
						continue;
					}
				}
			}
		}
	setTimeout("updateBoardView()", 200);
	
	return true;
}

function moveRight(){
	if(!canMoveRight(board))
		return false;
		
	for(var i = 0; i < 4; i++)
		for(var j = 2; j >= 0; j--){
			if(board[i][j] != 0){
				
				for(var k = 3; k > j; k--){
					if(board[i][k] == 0 && noBlockHorizontal(i, j, k, board)){
						
						showMoveAnimation(i, j, i, k);
						board[i][k] = board[i][j];
						board[i][j] = 0;
						continue;
					}
					else if(board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board) && !hasConflicted[i][k]){
						
						showMoveAnimation(i, j, i, k);
						board[i][k] += board[i][j];
						board[i][j] = 0;
						
						score += board[i][k];
						updateScore(score);
						hasConflicted[i][k] = true;
						continue;
					}
				}
			}
		}
	 setTimeout("updateBoardView()", 200);
	
	return true;
}

function moveDown(){
	if(!canMoveDown(board))
		return false;
		
	for(var j = 0; j < 4; j++)
		for(var i = 2; i >= 0; i--){
			if(board[i][j] != 0){
				
				for(var k = 3; k > i; k--){
					if(board[k][j] == 0 && noBlockVertical(j, i, k, board)){
						
						showMoveAnimation(i, j, k, j);
						board[k][j] = board[i][j];
						board[i][j] = 0;
						continue;
					}
					else if(board[k][j] == board[i][j] && noBlockVertical(j, i, k, board) && !hasConflicted[k][j]){
						
						showMoveAnimation(i, j, k, j);
						board[k][j] += board[i][j];
						board[i][j] = 0;
						
						score += board[k][j];
						updateScore(score);
						hasConflicted[k][j] = true;
						continue;
					}
				}
			}
		}
	 setTimeout("updateBoardView()", 200);
	return true;
}

function theMusic(){
	var audio = document.getElementById('music0');
	if(!musicStart){
		$('#ks').toggle();
		$('#zt').toggle();
		audio.play();
		musicStart = true;
	}
	else{
		$('#zt').toggle();
		$('#ks').toggle();
		audio.pause();
		musicStart = false;
	}
}